#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# File  : upload_proc.py
# Author: DaShenHan&道长-----先苦后甜，任凭晚风拂柳颜------
# Date  : 2019/7/12

from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import os
import time
import uuid #随机字符串

@csrf_exempt  # 取消csrf验证，否则会有403错误
def imageview(request):
    if request.method == 'POST':
        item = {}
        file = request.FILES.get('imgFile')
        ext_name = file.name.rfind('.')
        localtime = time.strftime('%Y/%m/%d', time.localtime())
        path = createfiles(localtime) + '/'
        print(path)
        file_name = str(uuid.uuid1()) + file.name[ext_name]
        file_path = os.path.join(path, file_name)
        print(file_path)

        with open(file_path, 'wb') as f:
            for temp in file.chunks():
                f.write(temp)
        item['message'] = '上传成功'
        item['url'] = '/' + file_path
        item['error'] = 0
        print(item['url'])
        return JsonResponse(item)


def createfiles(path):
    file_dirs = os.path.join(settings.BASE_DIR, 'media', 'test', path)
    path = os.path.join('media/test/', path)
    if not os.path.exists(path):
        os.makedirs(file_dirs)
    return path